﻿#include "Loading.h"
#include "LoadingRing.h"

#include <QPainter>
#include <QLabel>
#include <QVBoxLayout>
#include <QGraphicsDropShadowEffect>
#include <QEvent>

Loading::Loading(QWidget* parent, const QString& text)
    : QWidget(parent), m_text(text)
{
    setAttribute(Qt::WA_StyledBackground, true);
    setAttribute(Qt::WA_TranslucentBackground, true);
    setAttribute(Qt::WA_TransparentForMouseEvents, false);
    setAttribute(Qt::WA_DeleteOnClose, false);
    setWindowFlags(Qt::FramelessWindowHint | Qt::Tool);
    setVisible(false);

    // ---- 中心卡片 ----
    m_centerWidget = new QWidget(this);
    m_centerWidget->setObjectName("centerWidget");
    m_centerWidget->setFixedSize(180, 140);
    m_centerWidget->setStyleSheet(
        "#centerWidget {"
        "background: #eeeeeeee;"
        "border-radius: 16px;"
        "}"
        );

    // 阴影
    auto* eff = new QGraphicsDropShadowEffect;
    eff->setBlurRadius(35);
    eff->setOffset(0, 0);
    eff->setColor(QColor(0, 0, 0, 80));
    m_centerWidget->setGraphicsEffect(eff);

    // ---- 文本 ----
    QLabel* label = new QLabel(text, m_centerWidget);
    label->setAlignment(Qt::AlignHCenter | Qt::AlignBottom);

    // ---- 布局 ----
    QVBoxLayout* lay = new QVBoxLayout(m_centerWidget);
    lay->addWidget(new LoadingRing(this), 1, Qt::AlignCenter);
    lay->addWidget(label);

    if (parent) {
        setGeometry(parent->geometry());
        parent->installEventFilter(this);
    }
}

void Loading::start()
{
    if (!parentWidget()) return;

    setGeometry(parentWidget()->geometry());
    show();
}

void Loading::stop()
{
    hide();
    close();
    deleteLater();
}

void Loading::resizeEvent(QResizeEvent* event)
{
    QWidget::resizeEvent(event);
    // 让中心卡片居中
    m_centerWidget->move(
        (width() - m_centerWidget->width()) / 2,
        (height() - m_centerWidget->height()) / 2
        );
}

void Loading::paintEvent(QPaintEvent*)
{
    QPainter p(this);
    p.setRenderHint(QPainter::Antialiasing, true);

    // ---- 半透明遮罩 ----
    p.fillRect(rect(), QColor(0, 0, 0, 160));
}

bool Loading::eventFilter(QObject *watched, QEvent *event)
{
    if (parentWidget() && watched == parentWidget() &&
        (event->type() == QEvent::Resize || event->type() == QEvent::Move)) {
        setGeometry(parentWidget()->geometry());
    }
    return QWidget::eventFilter(watched, event);
}
